package com.funong.matrix.core.utils;

import com.funong.matrix.core.dto.Result;
import com.funong.matrix.core.enums.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(BusinessException.class)
    public Result businessException(BusinessException e) {
        log.error("业务异常:{}", e.getMessage(), e);
        return Result.failure(e.getCode(), e.getMessage());
    }


    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(RuntimeException.class)
    public Result runtimeException(RuntimeException e) {
        log.error("系统运行异常:{}", e.getMessage(), e);
        return Result.failure(505, e.getMessage());
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(Exception.class)
    public Result exception(Exception e) {
        log.error("系统异常:{}", e.getMessage(), e);
        return Result.failure(403, e.getMessage());
    }

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public Result handleVaildException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题{}，异常类型：{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            // 错误字段 、 错误提示
            errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
        });
        Result<Object> errorResult = new Result<>();
        errorResult.setData(errorMap);
        errorResult.setCode(ResultCodeEnum.PARAMS_MISS.getCode());
        FieldError fieldError = bindingResult.getFieldError();
        if (fieldError != null) {
            errorResult.setMessage(fieldError.getDefaultMessage());
        }
        return errorResult;
    }
}
